package bi.uc.client;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import bi.uc.login.Info;

import com.bi_uc.www.R;
import com.zijunlin.Zxing.Demo.CaptureActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/**
 * @author Administrator
 *
 */
public class ReadMemberInfoActivity extends Activity implements OnClickListener, Runnable {
	EditText cardNum;
	MyTextView cardType;
	MyTextView cardLevel;
	MyTextView cardUser;
	MyTextView score;
	MyTextView txTel;
	MyTextView money;
	Button more;
	Button read;
	Button btnOK;
	private PopupWindow popupWindow;
	private LinearLayout layout;
	private ListView listView;
	String error = "";	//读取信息失败时显示信息
	boolean bool;		//是否读取成功
	Info info = Info.getInfo(); 
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		((ExitApplication)getApplication()).addActivity(this);
		setContentView(R.layout.readmemberinfo);
		cardType = (MyTextView) findViewById(R.id.cardType);
		cardLevel = (MyTextView) findViewById(R.id.cardLevel);
		cardUser = (MyTextView) findViewById(R.id.cardUser);
		score = (MyTextView) findViewById(R.id.score);
		txTel = (MyTextView) findViewById(R.id.txTel);
		money = (MyTextView) findViewById(R.id.money);
		btnOK = (Button) findViewById(R.id.btnOK);
		cardNum =   (EditText) findViewById(R.id.cardNum);
		more = (Button) findViewById(R.id.more);
		more.setOnClickListener(this);
		read = (Button) findViewById(R.id.read);
		read.setOnClickListener(this);
		btnOK.setOnClickListener(this);
	}

	/* (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		case R.id.more:
			showPopupWindow();
			break;
		case R.id.read:
			((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(view.getWindowToken(), 0);  
			if (info.stopFlag) {
				Toast.makeText(this, "网络未连接，请确保您的网络已连接！", Toast.LENGTH_SHORT)
						.show();
			} else {
				apply();
			}
			break;
		case R.id.btnOK:
			if (!info.isExist(info.card.cardNum)) {
				Toast.makeText(this, "请读取会员信息！", Toast.LENGTH_SHORT)
				.show();
			}else {
				Intent intent = getIntent();
				setResult(RESULT_OK, intent);
				finish();
			}
			
			break;
		default:
			break;
		}
	}
	
	/**
	 * 
	 */
	private void apply() {
		// TODO Auto-generated method stub
		info.card.cardNum = cardNum.getText().toString();
		if (!info.isExist(info.card.cardNum)) {
			Toast.makeText(this, "请输入或扫描卡号！", Toast.LENGTH_SHORT).show();
			return;
		}
		new Thread(this).start();
	}

	public void showPopupWindow() {
		List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();		
		HashMap<String, Object> qrcodemap = new HashMap<String, Object>();			
		qrcodemap.put("drawable", R.drawable.qrcode);
		qrcodemap.put("text", "扫描二维码");
		list.add(qrcodemap);
		HashMap<String, Object> telmap = new HashMap<String, Object>();			
		telmap.put("drawable", R.drawable.mobile);
		telmap.put("text", "手机号码查找");
		list.add(telmap);
		layout = (LinearLayout) LayoutInflater.from(this).inflate(
				R.layout.dialog, null);
		listView = (ListView) layout.findViewById(R.id.lv_dialog);
//		listView.setAdapter(new ArrayAdapter<String>(this,
//				R.layout.text, R.id.tv_text, title)); 	
//		listView = new ListView(this);
//		listView.setBackground(getResources().getDrawable(R.drawable.click));
		
		
		listView.setAdapter(new MyAdapter(this, list, R.layout.text,
				new String[] { "drawable", "text" }, new int[] { R.id.img,
						R.id.tv_text }));
		popupWindow = new PopupWindow(listView, more.getWidth()*2, ViewGroup.LayoutParams.WRAP_CONTENT, true);
		popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));		
		popupWindow.setContentView(layout);
		popupWindow.showAsDropDown(more, 0, 0);
		

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?>  parent, View view, int position,
					long id) {
				switch (position) {
				case 0:
					popupWindow.dismiss();
					popupWindow = null;
					Log.d("tag", "扫描二维码");
					Intent intent1 = new Intent(ReadMemberInfoActivity.this, CaptureActivity.class);
					startActivityForResult(intent1, 1);
					break;
				default:
					popupWindow.dismiss();
					popupWindow = null;
					Log.d("tag", "手机号码查找");
					Intent intent = new Intent(ReadMemberInfoActivity.this, MobileSearchActivity.class);
					startActivityForResult(intent, 0);
					break;
				}
				
			}
			
		});
	}
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		  case 0:			//手机查找会员号码
		          if(resultCode==Activity.RESULT_OK){		        	  
		        	  cardNum.setText(data.getCharSequenceExtra("cardNum"));
		          }
		          break;
		  case 1:			//二维码扫描输入会员号码
	          if(resultCode==Activity.RESULT_OK){		        	  
	        	  cardNum.setText(data.getCharSequenceExtra("code"));
	          }
	          break;      
		   default:
			   break;
		  }
	}
	
	
	class MyAdapter extends SimpleAdapter {

		private List<HashMap<String, Object>> data;

		public MyAdapter(Context context, List<HashMap<String, Object>> data,
				int resource, String[] from, int[] to) {
			super(context, data, resource, from, to);
			this.data = data;
		}

		@Override
		public int getCount() {
			return data.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			System.out.println(position);
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = LayoutInflater.from(ReadMemberInfoActivity.this).inflate(
						R.layout.text, null);
				holder.img = (ImageView) convertView
						.findViewById(R.id.img);
				holder.text = (TextView) convertView.findViewById(R.id.tv_text);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.text.setText(data.get(position).get("text").toString());
			holder.img.setImageResource(Integer.parseInt(data.get(position).get("drawable").toString()));
			return convertView;
		}
	}

	class ViewHolder {
		private ImageView img;
		private TextView text;
	}

	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			send();			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onTouchEvent(android.view.MotionEvent)
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		InputMethodManager imm= (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		 if  (event.getAction() == MotionEvent.ACTION_DOWN) {  

             System.out.println("down" );  

             if  (this .getCurrentFocus() !=  null ) {  

                 if  (this .getCurrentFocus().getWindowToken() !=  null ) {  

                     imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),  

                             0);  

                 }  

             }  

         }  
		return super.onTouchEvent(event);
	}
	
	/**
	 * 
	 */
	private void send() throws Exception{
		String Url = "http://bi.bi-uc.com/BI.api";
		/*String Body = "Action=PDA-充值&商家=" + info.employID + "&店面="
				+ info.shopID + "&操作员=" + info.userID + "&卡号=" + cardNumString
				+ "&充值金额=" + moneyString;
		Log.d("data", Body);*/
		HttpPost httpRequest = new HttpPost(Url);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		NameValuePair pair1 = new BasicNameValuePair("Action", "PDA-读卡");
		NameValuePair pair2 = new BasicNameValuePair("商家", info.employID);				
		NameValuePair pair3 = new BasicNameValuePair("卡号", info.card.cardNum);
		NameValuePair pair4 = new BasicNameValuePair("店面", info.shopID);
		params.add(pair1);
		params.add(pair2);
		params.add(pair3);
		params.add(pair4);
		HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
		httpRequest.setEntity(entity);
		DefaultHttpClient client = new DefaultHttpClient();
		HttpResponse response = client.execute(httpRequest);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			/*InputStream in = response.getEntity().getContent();
			BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));  
			StringBuffer responseMessage = new StringBuffer();
			int charCount = -1;  
			while ((charCount = br.read()) != -1) {  
				responseMessage.append((char) charCount);  
				}  
			Log.d("tag", responseMessage.toString());} */
//			String ss = EntityUtils.toString(response.getEntity());  
//			Log.e("测试", ss);
//			InputStream in = new ByteArrayInputStream(ss.getBytes(HTTP.UTF_8));			
			InputStream in = response.getEntity().getContent();// 接收服务器的数据
			XmlPullParserFactory pullParserFactory = XmlPullParserFactory.newInstance();    // 获取XmlPullParser的实例					
			final XmlPullParser parser = pullParserFactory.newPullParser();
			InputStreamReader responseReader = new InputStreamReader(in,"UTF-8");
			parser.setInput(responseReader);
			
			parser.next();
			int eventType = parser.getEventType();
			if (eventType == XmlPullParser.START_TAG&& parser.getName().equals("XML")) { 
				// String result = parser.getAttributeValue(0);
				String result = parser.getAttributeValue(null, "EXEC");
				if (result.equals("True")) {								
					info.card.score = Integer.parseInt(parser.getAttributeValue(null, "pCard_可用积分"));
					info.card.money = Double.parseDouble(parser.getAttributeValue(null, "pCard_可用储值"));
					info.card.cardType = parser.getAttributeValue(null, "aCardType_名称");
					info.card.cardLevel = parser.getAttributeValue(null, "aCardTypeLevel_名称");
					info.card.cardUser = parser.getAttributeValue(null, "pMember_姓名");
					StringBuffer sb = new StringBuffer(parser.getAttributeValue(null, "pMember_手机"));
					sb.replace(3, 7, "****");
					info.card.tel = sb.toString();
					info.card.isScorePay = "1".equals(parser.getAttributeValue(null, "aCardTypeLevel_是否启用积分抵现")); //是否启用积分抵现
					info.card.scoreMoneyExchange = Double.parseDouble(parser.getAttributeValue(null, "aCardTypeLevel_积分抵现系数")); //积分抵现系数
					info.card.scoreMoneyRatio = Double.parseDouble(parser.getAttributeValue(null, "aCardTypeLevel_积分抵现上限比例")); //积分抵现上限比例
					info.card.Factor = Double.parseDouble(parser.getAttributeValue(null, "aCardTypeLevel_积分系数"));		//会员卡积分系数
					info.card.Discount = Double.parseDouble(parser.getAttributeValue(null, "aCardTypeLevel_折扣系数"));		//会员卡折扣
					
//					Log.d("data", "score="+info.card.score+", money="+parser.getAttributeValue(null, "pCard_可用储值")+", cardType="+info.card.cardType
//							+", cardLevel="+info.card.cardLevel+", cardUser="+info.card.cardUser+", tel="+info.card.tel+
//							", isScorePay="+parser.getAttributeValue(null, "aCardTypeLevel_是否启用积分抵现")
//							+", scoreMoneyExchange="+parser.getAttributeValue(null, "aCardTypeLevel_积分抵现系数")
//							+", Factor="+parser.getAttributeValue(null, "aCardTypeLevel_积分系数")
//							+", Discount="+parser.getAttributeValue(null, "aCardTypeLevel_折扣系数"));
//					Log.d("data", parser.getAttributeValue(null, "aCardTypeLevel_会员日折扣积分规则"));
					info.card.ruleArray = new JSONArray(parser.getAttributeValue(null, "aCardTypeLevel_会员日折扣积分规则"));
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							cardType.setText(info.card.cardType);
							cardLevel.setText(info.card.cardLevel);
							cardUser.setText(info.card.cardUser);
							score.setText(""+info.card.score);
							money.setText(info.subZeroAndDot(""+info.card.money));
							txTel.setText(info.card.tel);
						}
					});
				} 
				else 
				{
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							cardType.setText("");
							cardLevel.setText("");
							cardUser.setText("");
							score.setText("");	
							money.setText("");
							txTel.setText("");
							Toast.makeText(ReadMemberInfoActivity.this, parser.getAttributeValue(null, "错误消息"), Toast.LENGTH_SHORT).show();
						}
					});
				
					
				}				
			}
			in.close();				
			responseReader.close();	
		}
		else
		{
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(ReadMemberInfoActivity.this, "连接超时，请确保网络连接正常！", Toast.LENGTH_SHORT).show();
				}
			});			
		}
	}
}

class MyTextView extends TextView{
	public MyTextView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		Paint paint = new Paint();
		paint.setColor(Color.BLUE);
        canvas.drawLine(-1, getLineHeight()-1, this.getWidth()+1, getLineHeight()-1, paint);       
	}
	
}

class MyEditText extends EditText{
	public MyEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		Paint paint = new Paint();
		paint.setColor(Color.BLACK);
		// 画TextView的4个边.
		canvas.drawLine(0, 0, this.getWidth(), 0, paint);
		canvas.drawLine(0, 0, 0, this.getHeight(), paint);
		canvas.drawLine(this.getWidth() - 1, 0, this.getWidth() - 1,
				this.getHeight(), paint);
		canvas.drawLine(0, this.getHeight() - 1, this.getWidth(),
				this.getHeight() - 1, paint);     
	}
	
}